<template>
  <Dialog :title="currentRow.id ? '编辑人员' : '增加人员'" class="single-column" :loading="loading" :visible="visible" button-text="保存" @close="handleClose" @confirm="handleConfirm">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-row flex>
        <el-col>
          <el-form-item label="姓名：" prop="usrName">
            <el-input v-model="ruleForm.usrName" style="width: 235px;" />
          </el-form-item>
          <el-form-item label="手机：" prop="phone">
            <el-input v-model="ruleForm.phone" style="width: 235px;" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="4" :offset="8">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          上传图片
        </el-col> -->
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="性别：" prop="sex">
            <el-select v-model="ruleForm.sex" placeholder="请选择" class="el-select-y">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="医院：" prop="hospitalId">
            <el-select v-model="ruleForm.hospitalId" placeholder="请选择" class="el-select-y" @change="nameSelect">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.hospitalName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row flex>
        <el-col>
          <el-form-item label="部门：" prop="deptUsr">
            <!-- multiple 多选 -->
            <el-select
              v-model="ruleForm.deptUsr"
              collapse-tags
              placeholder="请选择"
              class="el-select-y"
              value-key="id"
              @change="deptUsrList"
            >
              <el-option
                v-for="item in department"
                :key="item.id"
                :label="item.deptName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="2" :offset="1">
          <el-button type="text">+增加</el-button>
        </el-col> -->
      </el-row>
      <el-row flex>
        <el-col>
          <el-form-item label="岗位：" prop="usrJob">
            <!-- multiple 多选 -->
            <el-select
              v-model="ruleForm.usrJob"
              collapse-tags
              placeholder="请选择"
              class="el-select-y"
              @change="usrJobList"
            >
              <el-option
                v-for="item in allJobList"
                :key="item.id"
                :label="item.jobName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="2" :offset="1">
          <el-button type="text">+增加</el-button>
        </el-col> -->
      </el-row>
      <!-- <el-row flex>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" />
          </el-form-item>
        </el-col>
        <span class="font-style">随机生成</span>
        <span class="font-style">复制密码</span>
      </el-row> -->
      <!-- <el-row flex>
        <el-col :span="10">
          <el-form-item label="组员">
            <el-select
              v-model="ruleForm"
              multiple
              collapse-tags
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-form-item label="状态：" prop="status">
        <el-radio v-model="ruleForm.status" label="在职" />
        <el-radio v-model="ruleForm.status" label="离职" />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script>
import { setLocalStorage } from "@monkey.do/monkey";
import Dialog from "@/components/Dialog";
export default {
  components: { Dialog },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    currentRow: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    var validatorPhone = function(rule, value, callback) {
      console.log(value);
      if (!value) {
        callback(new Error('请输入手机号'));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号格式错误'));
      } else {
        callback();
      }
    };
    return {
      props: { multiple: true },
      ruleForm: {
        status: "在职",
      },
      value: '',
      imageUrl: '',
      options: [],
      option: [],
      department: [],
      allJobList: [],
      rules: {
        usrName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        phone: [
          { required: true, validator: validatorPhone, trigger: 'blur' },
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' },
        ],
        hospitalId: [
          { required: true, message: '请选择医院', trigger: 'change' },
        ],
        usrJob: [
          { required: true, message: '请选择岗位', trigger: 'blur' },
        ],
        deptUsr: [
          { required: true, message: '请选择部门', trigger: 'blur' },
        ],
      },
      loading: false,
    };
  },
  watch: {
    currentRow: {
      handler(val) {
        this.ruleForm = JSON.parse(JSON.stringify(val));
        console.log(this.ruleForm);
      },
      deep: true,
    },
  },
  mounted() {
    this.getAllHospital();
    this.getAllDepartment();
    this.getAllJob();
  },
  methods: {
    async getAllHospital() {
      const res = await this.$api['data/dept/getAllHospital']();
      if (res.code !== 200) return;
      this.options = res.data;
    },
    async getAllDepartment() {
      const res = await this.$api['data/hospitalStaff/getAllDepartment']();
      if (res.code !== 200) return;
      this.department = res.data;
    },
    async getAllJob() {
      const res = await this.$api['data/hospitalStaff/getAllJob']();
      if (res.code !== 200) return;
      this.allJobList = res.data;
    },
    handleChange(value) {
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    handleClose() {
      this.$emit('update:visible', false);
      this.$emit('update:currentRow', {});
      this.$refs.ruleForm.resetFields();
      this.ruleForm = { status: "在职" };
      this.loading = false;
    },
    handleConfirm() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return;
        this.loading = true;
        if (this.currentRow.id) {
          const deptUsr = this.currentRow.deptUsrList;
          const usrJob = this.currentRow.usrJobList;
          if (deptUsr && deptUsr.length > 0) {
            if (this.ruleForm.deptUsr.length === deptUsr.length) {
              let isTrue = false;
              for (let i = 0; i < this.ruleForm.deptUsr.length; i++) {
                if (deptUsr.indexOf(this.ruleForm.deptUsr[i]) === -1) {
                  isTrue = true;
                  break;
                }
              }
              if (!isTrue) this.ruleForm.deptUsrList = [];
            }
          }
          if (this.ruleForm.usrJob.length === usrJob.length) {
            let isTrue = false;
            for (let i = 0; i < this.ruleForm.usrJob.length; i++) {
              if (usrJob.indexOf(this.ruleForm.usrJob[i]) === -1) {
                isTrue = true;
                break;
              }
            }
            if (!isTrue) this.ruleForm.usrJobList = [];
          }
          this.$api[`data/hospitalStaff/modifyHisusr`](this.ruleForm).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.msgSuccess('修改人员成功');
            this.handleClose();
          }).finally(() => (this.loading = false));
        } else {
          this.$api[`data/hospitalStaff/addHisusr`](this.ruleForm).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.msgSuccess('增加人员成功');
            this.loadHisUsr();
            this.handleClose();
          }).finally(() => (this.loading = false));
        }
      });
    },
    nameSelect(id) {
      this.options.forEach(item => {
        if (item.id === id) {
          this.ruleForm.hospitalName = item.hospitalName;
        }
      });
    },
    deptUsrList(val) {
      const list = [];
      this.department.forEach(item => {
        if (val.indexOf(item.id) > -1) list.push({ deptId: item.id, deptName: item.deptName });
      });
      this.ruleForm.deptUsrList = list;
    },
    usrJobList(val) {
      const list = [];
      this.allJobList.forEach(item => {
        if (val.indexOf(item.id) > -1) list.push({ hospitalJobId: item.id, hospitalJobName: item.jobName });
      });
      this.$set(this.ruleForm, "usrJobList", list);
    },
    loadHisUsr() {
      // 拉取当前登陆医院的所有医院用户
      this.$api['doctor/consulting/getAllUsr']().then(resData => {
        if (resData.data) {
          setLocalStorage("HIS_USR_LIST", resData.data);
        }
      })
        .catch(err => {
          console.error(err);
          this.$message.error('拉取医院用户失败');
        });
    },
  },
};
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
  .font-style{
    line-height: 32px;
    margin-left: 20px;
    cursor: pointer;
  }
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
